package com.wangsd.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wangsd.core.entity.JSONResult;
import com.wangsd.core.util.*;
import com.wangsd.core.util.excel.EasyExcel;
import com.wangsd.web.model.*;
import com.wangsd.web.modelCustom.*;
import com.wangsd.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公共视图控制器
 *
 **/
@Controller
public class CommonController {

    @Autowired
    MenuService menuService;
    @Autowired
    HousinginfoService housinginfoService;
    @Autowired
    RoominfoService roominfoService;
    @Autowired
    BillAccountService billAccountService;
    @Autowired
    CosttypeService costtypeService;
    @Autowired
    PropertyinfoService propertyinfoService;
    @Autowired
    DirectFeeService directFeeService;

    /**
     * 进入首页
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model) {
        UserCustom obj = (UserCustom) request.getSession().getAttribute("userInfo");
        Integer roleId = obj.getRoleId();
        List<MenuCustom> list = menuService.queryMenuByRoleId(roleId);
        model.addAttribute("menuList", list);
        return "/index";
    }

    /**
     * 打开导入房屋Excel页面
     *
     * @param model
     * @return
     */
    @RequestMapping(path = "/openRoomExcel")
    public String openExcel(Model model) {
        return "/roominfo/roomExcel";
    }

    /**
     * 打开导入账单Excel页面
     *
     * @param model
     * @return
     */
    @RequestMapping(path = "/openBillExcel")
    public String openBillExcel(Model model) {
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        return "/billaccount/billExcel";
    }

    /**
     * 导入Excel（房屋）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
	@RequestMapping(path = "/uploadExcel")
    @ResponseBody
    public JSONResult uploadExcel(HttpServletRequest request) throws Exception {
        JSONResult jsonResult = new JSONResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("upfile");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        InputStream in = file.getInputStream();
        EasyExcel fastExcel = new EasyExcel(in);
        fastExcel.setSheetName("Sheet1");
        List<BillExcelBean> list = fastExcel.parse(BillExcelBean.class);
        fastExcel.close();
        if(null != list && !list.isEmpty()) {
            return roominfoService.importRoominfo(list);
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("数据为空");
            return jsonResult;
        }
    }

    /**
     * 导入Excel（账单）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
	@RequestMapping(path = "/uploadBillExcel")
    @ResponseBody
    public JSONResult uploadBillExcel(HttpServletRequest request) throws Exception {
        JSONResult jsonResult = new JSONResult();
        String costType = request.getParameter("costType");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("upfile");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        InputStream in = file.getInputStream();
        EasyExcel fastExcel = new EasyExcel(in);
        fastExcel.setSheetName("Sheet1");
        List<BillExcelBean> list = fastExcel.parse(BillExcelBean.class);
        fastExcel.close();
        if(null != list && !list.isEmpty()) {
            return billAccountService.importBillaccount(list, Integer.parseInt(costType));
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("数据为空");
            return jsonResult;
        }
    }
    /**
     * 下载模板
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadRoominfo")
    public void downloadRoominfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        request.setCharacterEncoding("UTF-8");
        String rootpath = request.getSession().getServletContext().getRealPath("/");
        String fileName = "import.xlsx";
        try {
            File f = new File(rootpath + "download/" + fileName);
            response.setContentType("application/x-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(f.length()));
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while (-1 != (len = in.read(data, 0, data.length))) {
                out.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 开电子发票
     * @param ids
     * @param
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
	@RequestMapping(path = "/nuonuoInvoice")
    @ResponseBody
    public JSONResult nuonuoInvoice(Integer[] ids,InvoiceTitle invoiceTitleNew) throws Exception {
    	Integer[] nums=ArrayUtils.duplicateRemoval(ids);
    	JSONResult jsonResult = new JSONResult();
        boolean bl = false;
        InvoiceTitle invoiceTitle = new InvoiceTitle();
        List<InvoiceTitleDetail> detailList = new ArrayList<>();
        Propertyinfo propertyinfo=null;
        for (Integer id : nums) {
            Billaccount billaccount = billAccountService.selectBillAccountById(id);
            Roominfo roominfo = roominfoService.selectRoominfoById(billaccount.getRoominfoId());
            if (invoiceTitle.getBuyerPhone() != null && !roominfo.getOwnerPhone().equals(invoiceTitle.getBuyerPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请选择同一业主的数据");
                return jsonResult;
            }
            Housinginfo housing = housinginfoService.selectHousinginfoById(billaccount.getHousingId());
            propertyinfo = propertyinfoService.selectPropertyinfoById(housing.getParentId());
            Costtype costtype = costtypeService.selectCosttypeById(billaccount.getCostType());
            //发票明细
            InvoiceTitleDetail detail = new InvoiceTitleDetail();
            detail.setGoodsCode("304080101");
            detail.setGoodsName(costtype.getName());
            detail.setSpecType(billaccount.getAcctPeriod());
            detail.setTaxRate(costtype.getTaxrate().toString());
            detail.setWithTaxFlag("1");
            detail.setNum("1");
            detail.setPrice(billaccount.getBillEntryAmount().toString());
            detailList.add(detail);
            //发票主体
            invoiceTitle.setBuyerName(roominfo.getOwnerName() + "-" + roominfo.getAddress());
            String phone=invoiceTitleNew.getBuyerPhone();
            String phoneNew=roominfo.getOwnerPhone();
            if(phoneNew!=null&&!"".equals(phoneNew)){
            	invoiceTitle.setBuyerPhone(phoneNew);
            }else{
            	invoiceTitle.setBuyerPhone(phone);
            }
            String buyerTaxNum=invoiceTitleNew.getBuyerTaxNum();
            if(buyerTaxNum!=null&&!"".equals(buyerTaxNum)){
            	invoiceTitle.setBuyerTaxNum(buyerTaxNum);
            }
            invoiceTitle.setOrderNo(String.valueOf(System.currentTimeMillis()));
            invoiceTitle.setClerk("系统");
            invoiceTitle.setInvoiceDate(DateUtils.getCurDatetime());
            invoiceTitle.setSalerTel(propertyinfo.getContactPhone());
            invoiceTitle.setSalerAddress(propertyinfo.getContactAddress());
            invoiceTitle.setSalerTaxNum(propertyinfo.getSalertaxnum());
			invoiceTitle.setSalerAccount(propertyinfo.getSaleraccount());
            invoiceTitle.setPushMode("1");
        	invoiceTitle.setInvoiceType("1");
        	invoiceTitle.setRemark(ApplicationUtils.getPayType(billaccount.getPaytype()));
        }
        invoiceTitle.setInvoiceDetail(detailList);
        NuoNuoUtil nuoNuoUtil = new NuoNuoUtil();
        JSONObject data =nuoNuoUtil.send(invoiceTitle,propertyinfo);
		//token已经过期
		if("070301".equals(data.get("code"))){
			//获取token
			Map<String, String> params = new HashMap();
			params.put("client_id", propertyinfo.getNuonuoAppkey());
			params.put("client_secret", propertyinfo.getNuonuoSecret());
			params.put("grant_type", "client_credentials");
			String aa = HttpUtil.doPost("https://open.jss.com.cn/accessToken", params);
			//修改数据库tonken
			JSONObject jsonObject = JSONObject.parseObject(aa);
			propertyinfo.setNuonuoAccesstoken(jsonObject.get("access_token").toString());
			propertyinfoService.updateProperty(propertyinfo);
			jsonResult.setMessage("请重试");
			jsonResult.setSuccess(bl);
			return jsonResult;
		}
        String invoiceSerialNum =  data.getJSONObject("result").getString("invoiceSerialNum");
        if (invoiceSerialNum != null) {
            for (Integer id : nums) {
            	Billaccount bill = new Billaccount();
                bill.setId(id);
                bill.setTicketstatus(StaticVar.BILLACCOUNT_TICKETSTATUS1);
                bill.setInvoiceserialnum(invoiceSerialNum);
                bl = billAccountService.updateBillaccount(bill);
            }
        }
        if (bl) {
            jsonResult.setMessage("开票成功");
        }else{
            jsonResult.setMessage("开票失败");
        }
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     *
     * Description: 退票
     * @param
     * @param remark
     * @return
     * @throws Exception
     */
	@SuppressWarnings("rawtypes")
	@RequestMapping(path = "/rejectNuoNuoInvoice")
    @ResponseBody
    public JSONResult rejectNuoNuoInvoice(Integer id,String remark,String buyerTaxNum) throws Exception{
		NuoNuoUtil nuoNuoUtil = new NuoNuoUtil();
		JSONResult jsonResult = new JSONResult();
		boolean bl = false;
		InvoiceTitle invoiceTitle = new InvoiceTitle();
		List<InvoiceTitleDetail> detailList = new ArrayList<InvoiceTitleDetail>();
		Propertyinfo propertyinfo = null;
		Billaccount billaccount = billAccountService.selectBillAccountById(id);
		List<Billaccount> list=billAccountService.selectBillAccountByInvoiceserialnum(billaccount.getInvoiceserialnum());
		for (Billaccount billaccount1 : list) {
			Roominfo roominfo = roominfoService.selectRoominfoById(billaccount1.getRoominfoId());
			Housinginfo housing = housinginfoService.selectHousinginfoById(billaccount1.getHousingId());
			propertyinfo = propertyinfoService.selectPropertyinfoById(housing.getParentId());
			Costtype costtype = costtypeService.selectCosttypeById(billaccount1.getCostType());
			// 发票明细
			InvoiceTitleDetail detail = new InvoiceTitleDetail();
            detail.setGoodsCode("304080101");
            detail.setGoodsName(costtype.getName());
            detail.setSpecType(billaccount.getAcctPeriod());
			detail.setTaxRate(costtype.getTaxrate().toString());
			detail.setWithTaxFlag("1");
			detail.setNum("-1");
			detail.setPrice(billaccount1.getBillEntryAmount().toString());
			detailList.add(detail);
			// 发票主体
			invoiceTitle.setBuyerName(roominfo.getOwnerName() + "-" + roominfo.getAddress());
			invoiceTitle.setBuyerTaxNum(buyerTaxNum);
			invoiceTitle.setBuyerPhone(roominfo.getOwnerPhone());
			invoiceTitle.setOrderNo(String.valueOf(System.currentTimeMillis()));
			invoiceTitle.setClerk("系统");
			invoiceTitle.setInvoiceDate(DateUtils.getCurDatetime());
			invoiceTitle.setSalerTel(propertyinfo.getContactPhone());
			invoiceTitle.setSalerAddress(propertyinfo.getContactAddress());
			invoiceTitle.setSalerTaxNum(propertyinfo.getSalertaxnum());
			invoiceTitle.setPushMode("1");
			invoiceTitle.setInvoiceType("2");
			invoiceTitle.setRemark(remark);
			// 开票成功查询发票代码和号码
			JSONObject data1 = nuoNuoUtil.query(billaccount1.getInvoiceserialnum(), propertyinfo);
			String invoiceCode = data1.getJSONArray("result").getJSONObject(0).getString("invoiceCode");
			String invoiceNum = data1.getJSONArray("result").getJSONObject(0).getString("invoiceNum");
			invoiceTitle.setInvoiceCode(invoiceCode);
			invoiceTitle.setInvoiceNum(invoiceNum);
		}
		invoiceTitle.setInvoiceDetail(detailList);
		JSONObject data = nuoNuoUtil.send(invoiceTitle,propertyinfo);
		if("".equals(data.getString("result"))){
			jsonResult.setMessage(data.getString("describe"));
			jsonResult.setSuccess(false);
			return jsonResult;
		}
		String invoiceSerialNum = data.getJSONObject("result").getString("invoiceSerialNum");
		if (invoiceSerialNum != null) {
			for (Billaccount billaccount2 : list) {
				Billaccount bill = new Billaccount();
				bill.setId(billaccount2.getId());
				// 退票
				bill.setTicketstatus(StaticVar.BILLACCOUNT_TICKETSTATUS2);
				bl = billAccountService.updateBillaccount(bill);
			}
		}
		if (bl) {
			jsonResult.setMessage("退票成功");
		} else {
			jsonResult.setMessage("退票失败");
		}
		jsonResult.setSuccess(bl);
		return jsonResult;
    }

	/**
	 *
	 * Description: 直接费用开电子发票
	 * @param id
	 * @return
	 * @throws Exception
	 */
    @SuppressWarnings("rawtypes")
	@RequestMapping(path = "/nuonuoInvoiceByDirectfee")
    @ResponseBody
	public JSONResult nuonuoInvoiceByDirectfee(Integer id,HttpServletRequest request,InvoiceTitle invoiceTitleNew) throws Exception {
    	JSONResult jsonResult = new JSONResult();
		boolean bl = false;
    	UserCustom obj = (UserCustom) request.getSession().getAttribute("userInfo");
    	int type=obj.getType();
    	Propertyinfo propertyinfo = null;
    	int parentId=obj.getParentId();
    	if(type==2){
    		propertyinfo=propertyinfoService.selectPropertyinfoById(parentId);
    	}else if(type==3){
    		Housinginfo housinginfo=housinginfoService.selectHousinginfoById(parentId);
    		propertyinfo=propertyinfoService.selectPropertyinfoById(housinginfo.getParentId());
    	}else{
    		jsonResult.setMessage("此登录人不具开票功能");
    		jsonResult.setSuccess(bl);
    		return jsonResult;
    	}
    	Directfee directfee=directFeeService.selectByPrimaryKey(id);
		InvoiceTitle invoiceTitle = new InvoiceTitle();
		List<InvoiceTitleDetail> detailList = new ArrayList<>();
		// 发票明细
		InvoiceTitleDetail detail = new InvoiceTitleDetail();
        detail.setGoodsCode("304080101");
        detail.setGoodsName("物业服务费");
        detail.setSpecType(directfee.getProjectid());
		detail.setTaxRate("0.06");
		detail.setWithTaxFlag("1");
		detail.setNum("1");
		detail.setPrice(directfee.getFee().toString());
		detailList.add(detail);
		// 发票主体
		invoiceTitle.setBuyerName(directfee.getFeeUnit());
		String phone=invoiceTitleNew.getBuyerPhone();
        String phoneNew=directfee.getPhone();
        if(phoneNew!=null&&!"".equals(phoneNew)){
        	invoiceTitle.setBuyerPhone(phoneNew);
        }else{
        	invoiceTitle.setBuyerPhone(phone);
        }
        String buyerTaxNum=invoiceTitleNew.getBuyerTaxNum();
        if(buyerTaxNum!=null&&!"".equals(buyerTaxNum)){
        	invoiceTitle.setBuyerTaxNum(buyerTaxNum);
        }
		invoiceTitle.setOrderNo(String.valueOf(System.currentTimeMillis()));
		invoiceTitle.setClerk("系统");
		invoiceTitle.setInvoiceDate(DateUtils.getCurDatetime());
		invoiceTitle.setSalerTel(propertyinfo.getContactPhone());
		invoiceTitle.setSalerAddress(propertyinfo.getContactAddress());
		invoiceTitle.setSalerTaxNum(propertyinfo.getSalertaxnum());
		invoiceTitle.setSalerAccount(propertyinfo.getSaleraccount());
		invoiceTitle.setPushMode("1");
		invoiceTitle.setInvoiceType("1");
		invoiceTitle.setInvoiceDetail(detailList);
		invoiceTitle.setRemark(ApplicationUtils.getPayType(directfee.getPayType()));
		NuoNuoUtil nuoNuoUtil = new NuoNuoUtil();
		JSONObject data = nuoNuoUtil.send(invoiceTitle, propertyinfo);
		String invoiceSerialNum = data.getJSONObject("result").getString("invoiceSerialNum");
		if (invoiceSerialNum != null) {
			Directfee directfeeNew = new Directfee();
			directfeeNew.setId(id);
			directfeeNew.setTicketstatus(StaticVar.BILLACCOUNT_TICKETSTATUS1);
			directfeeNew.setInvoiceserialnum(invoiceSerialNum);
			int num = directFeeService.updateByPrimaryKeySelective(directfeeNew);
		    if(num==1){
			    bl=true;
		    }else{
		    	bl=false;
		    }
		}
		if (bl) {
			jsonResult.setMessage("开票成功");
		} else {
			jsonResult.setMessage("开票失败");
		}
		jsonResult.setSuccess(bl);
		return jsonResult;
	}

   /**
    *
    * Description: 直接费用退票
    * @param id
    * @param remark
    * @return
    * @throws Exception
    */
	@SuppressWarnings("rawtypes")
	@RequestMapping(path = "/rejectNuoNuoInvoiceByDirectfee")
    @ResponseBody
	public JSONResult rejectNuoNuoInvoiceByDirectfee(Integer id, HttpServletRequest request, String remark,String buyerTaxNum)
			throws Exception {
		JSONResult jsonResult = new JSONResult();
		boolean bl = false;
		UserCustom obj = (UserCustom) request.getSession().getAttribute("userInfo");
		int type = obj.getType();
		Propertyinfo propertyinfo = null;
		int parentId = obj.getParentId();
		if (type == 2) {
			propertyinfo = propertyinfoService.selectPropertyinfoById(parentId);
		} else if (type == 3) {
			Housinginfo housinginfo = housinginfoService.selectHousinginfoById(parentId);
			propertyinfo = propertyinfoService.selectPropertyinfoById(housinginfo.getParentId());
		} else {
			jsonResult.setMessage("此登录人不具退票功能");
			jsonResult.setSuccess(bl);
			return jsonResult;
		}
		Directfee directfee = directFeeService.selectByPrimaryKey(id);
		NuoNuoUtil nuoNuoUtil = new NuoNuoUtil();
		InvoiceTitle invoiceTitle = new InvoiceTitle();
		List<InvoiceTitleDetail> detailList = new ArrayList<InvoiceTitleDetail>();
		// 发票明细
		InvoiceTitleDetail detail = new InvoiceTitleDetail();
        detail.setGoodsCode("304080101");
        detail.setGoodsName("物业服务费");
        detail.setSpecType(directfee.getProjectid());
		detail.setTaxRate("0.06");
		detail.setWithTaxFlag("1");
		detail.setNum("-1");
		detail.setPrice(directfee.getFee().toString());
		detailList.add(detail);
		// 发票主体
		invoiceTitle.setBuyerName(directfee.getFeeUnit());
		invoiceTitle.setBuyerTaxNum(buyerTaxNum);
		invoiceTitle.setBuyerPhone(directfee.getPhone());
		invoiceTitle.setOrderNo(String.valueOf(System.currentTimeMillis()));
		invoiceTitle.setClerk("系统");
		invoiceTitle.setInvoiceDate(DateUtils.getCurDatetime());
		invoiceTitle.setSalerTel(propertyinfo.getContactPhone());
		invoiceTitle.setSalerAddress(propertyinfo.getContactAddress());
		invoiceTitle.setSalerTaxNum(propertyinfo.getSalertaxnum());
		invoiceTitle.setPushMode("1");
		invoiceTitle.setInvoiceType("2");
		invoiceTitle.setRemark(remark);
		// 开票成功查询发票代码和号码
		JSONObject data1 = nuoNuoUtil.query(directfee.getInvoiceserialnum(), propertyinfo);
		String invoiceCode = data1.getJSONArray("result").getJSONObject(0).getString("invoiceCode");
		String invoiceNum = data1.getJSONArray("result").getJSONObject(0).getString("invoiceNum");
		invoiceTitle.setInvoiceCode(invoiceCode);
		invoiceTitle.setInvoiceNum(invoiceNum);
		invoiceTitle.setInvoiceDetail(detailList);
		JSONObject data = nuoNuoUtil.send(invoiceTitle, propertyinfo);
		if("".equals(data.getString("result"))){
			jsonResult.setMessage(data.getString("describe"));
			jsonResult.setSuccess(false);
			return jsonResult;
		}
		String invoiceSerialNum = data.getJSONObject("result").getString("invoiceSerialNum");
		if (invoiceSerialNum != null) {
			Directfee directfeeNew = new Directfee();
			directfeeNew.setId(id);
			directfeeNew.setTicketstatus(StaticVar.BILLACCOUNT_TICKETSTATUS2);
			int num = directFeeService.updateByPrimaryKeySelective(directfeeNew);
			if (num == 1) {
				bl = true;
			} else {
				bl = false;
			}
		}
		if (bl) {
			jsonResult.setMessage("退票成功");
		} else {
			jsonResult.setMessage("退票失败");
		}
		jsonResult.setSuccess(bl);
		return jsonResult;
	}

}
